package src;

import java.io.*;
import java.nio.Buffer;


public class StudentData {
    private static String path = "src/studentdata.txt";
    private static int MaxSize = 100000;
    public Student[] stdsdata = new Student[MaxSize];
    public int capacity = 0;


    public int getFileDate() throws IOException{//读取文件内容
        int i = 0;

            FileInputStream fi = new FileInputStream(path);
            InputStreamReader isr = new InputStreamReader(fi,"UTF-8");
            BufferedReader reader = new BufferedReader(isr);
            String content;

            while ((content = reader.readLine()) != null) {
                if(i >= stdsdata.length) {
                    System.out.println("data full!");
                    break;
                }
                String[] data = content.split(" ");
                // 处理读取到的一行字符串
                Student stu = new Student(data[0],data[1],data[2],data[3],data[4],data[5]);
                stdsdata[i] = stu;
                i++;
            }
            capacity = i;
            reader.close();
            isr.close();
            fi.close();

            return capacity;//实际长度
    }

    public void setAllStudents(Student[] std,int capacity) throws IOException{//将缓存区内容重写至文件中
        FileOutputStream fo = new FileOutputStream(path);
        OutputStreamWriter osw = new OutputStreamWriter(fo,"UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);
        for(int i=0;i<capacity;i++) {
            bw.write(std[i].textData()+ "\n");
        }

        bw.close();
        osw.close();
        fo.close();

    }

    public void addFileData(Student std) throws IOException {//写入一名学生的信息
        FileOutputStream fo = new FileOutputStream(path,true);
        OutputStreamWriter osw = new OutputStreamWriter(fo,"UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);

            bw.write(std.textData()+"\n");

        bw.close();
        osw.close();
        fo.close();

    }

    public int findData(Student[] stdsData,int len,String number){//查找学生所在位置，成功返回数组下标，不在则-1
        for(int i = 0 ; i < len ; i++){
            if(stdsData[i].getNumber().equals(number)){

                return i;

            };
        }
        return -1;
    }

    public String createNumber(Student[] stdsData){//生成学号信息
       int rearnum = capacity;
        String Number = "2021096"+String.format("%05d",rearnum);
        while(findData(stdsData,capacity,Number)!=-1){
            rearnum++;
            if(rearnum >= MaxSize) rearnum = rearnum - MaxSize;//防止学号的长度无限增量,假定不超过十万名学生
            Number = "2021096"+String.format("%05d",rearnum);

        }
        return Number;

    }

    public boolean isFull(){//判满
        return capacity >= MaxSize;
    }



}
